//
//  Storage.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/6.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "Storage.h"
#import "MainConfigure.h"
#import <YYCache.h>
#import <YYImageCache.h>
static NSString * const KAuthorizationToken = @"KAuthorizationToken";
static NSString * const KAuthorizationUserID = @"KAuthorizationUserID";

static NSString * const kUserAccountKey = @"user_account";

NSString * const KTLoginSuccessNotificationKey = @"LoginSuccess";           //成功登录通知码
NSString * const KTOrginalAddressNotificationKey = @"OrginalAddressChange"; //地址更改

//用户信息key
NSString * const kAddressKey = @"OriginalAddress";
NSString * const kUsernameKey = @"UserAccountKey";
NSString * const kUserPasswordKey = @"UserPasswordKey";


#define SM_CART_SECTION_SELECTION_KEY @"SM_CART_SECTION_SELECTION_KEY"
#define SM_CART_SELECTION_KEY @"SM_CART_SELECTION_KEY"

#define FileManager [NSFileManager defaultManager]
#define  KTCacheDirectory ((NSString *)[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) lastObject])
#define KTHttpCacheDirectory [KTCacheDirectory stringByAppendingPathComponent:@"http_get_cache"]


@interface Storage ()

@end

@implementation Storage
{
    id _authorizationToken;
}
static Storage * shareInstance = nil;
//MARK: GETTERS
- (UIButton *)cartButton
{
    if (!_cartButton) {
        _cartButton = [UIButton new];
        [_cartButton setImage:SMPNGImage(@"cart_btn_50x50_") forState:UIControlStateNormal];
        [_cartButton addSubview:self.badgeView];
        _cartButton.contentEdgeInsets = UIEdgeInsetsMake(SM_SIZE(20), SM_SIZE(20), SM_SIZE(20), SM_SIZE(20));
        [_badgeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_cartButton.mas_top).offset(SM_SIZE(60));
            make.left.equalTo(_cartButton.mas_right).offset(SM_SIZE(-60));
            make.width.mas_greaterThanOrEqualTo(SM_SIZE(40));
            make.height.equalTo(@(SM_SIZE(40)));
        }];
    }
    return _cartButton;
}

- (UIButton *)badgeView
{
    if (!_badgeView) {
        _badgeView = [UIButton new];
        _badgeView.userInteractionEnabled = NO;
        _badgeView.backgroundColor = SM_dotRedColor;
        _badgeView.titleLabel.font = SM_NFont(25);
        [_badgeView setTitleColor:SM_whiteColor forState:UIControlStateNormal];
        _badgeView.layer.cornerRadius = SM_SIZE(40)/2.f;
        _badgeView.clipsToBounds = YES;
        _badgeView.contentEdgeInsets = UIEdgeInsetsMake(SM_SIZE(15), SM_SIZE(15), SM_SIZE(15), SM_SIZE(15));
        _badgeView.hidden = YES;
    }
    return _badgeView;
}




+ (instancetype)shareInstance{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        shareInstance = [[self alloc] init];

    });

    return shareInstance;
}


- (void)setAccount:(OMAccount *)account
{
    if (!account) {
        [SMUserDefault removeObjectForKey:kUserAccountKey];
        [OMAnalyzer userLogoutCollect];
    }else {
        SMUserDefaultSet(kUserAccountKey, [account mj_keyValues]);
        SMNotificationPost(KTLoginSuccessNotificationKey, nil);
        [OMAnalyzer userLoginCollect];
    }
}

- (OMAccount *)account
{
    if (![self.class isLogin]) {
        return nil;
    }
    NSDictionary *dic = SMUserDefaultGet(kUserAccountKey);
    return [OMAccount mj_objectWithKeyValues:dic];
}

- (void)setOriginalAddress:(OMOriginalAddress *)originalAddress
{
    if (!originalAddress) {
        [SMUserDefault removeObjectForKey:kAddressKey];
    }else {
        SMUserDefaultSet(kAddressKey, [originalAddress mj_keyValues]);
        SMNotificationPost(KTOrginalAddressNotificationKey, nil);
    }
}

- (OMOriginalAddress *)originalAddress
{
    NSDictionary *dic = SMUserDefaultGet(kAddressKey);
    return [OMOriginalAddress mj_objectWithKeyValues:dic];
}


+ (BOOL)isLogin
{
    return [SMUserDefaultGet(@"IS_LOGIN") boolValue];

}

+ (void)setLogin:(BOOL)isLogin
{
    SMUserDefaultSet(@"IS_LOGIN", @(isLogin));
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        SMNotificationPost(isLogin?OM_NOTIFICATION_KEY_LOGIN_SUCCESS:OM_NOTIFICATION_KEY_LOGOUT_SUCCESS, nil);
        if (!isLogin) {
            [Navigator logoutActionWithCompletion:^{

            }];
//            [KTHttpUtils clearCookies];
        }

    });

}

- (void)setNumOfCartItem:(NSUInteger)numOfCartItem
{
    SMUserDefaultSet(@"numOfCartItem", @(numOfCartItem));
    SMNotificationPost(OMSHOPPINGCART_BADAGE_NUM_CHANGE_NOTIFICATION, @(numOfCartItem));
    [Navigator setShoppingCartBadage:numOfCartItem];
}

- (NSUInteger)numOfCartItem
{
    return [SMUserDefaultGet(@"numOfCartItem") unsignedIntegerValue];
}

- (void)setUsername:(NSString *)userAccount
{
    SMUserDefaultSet(kUsernameKey,userAccount);
}

- (NSString *)username
{
    return SMUserDefaultGet(kUsernameKey);
}

- (NSString *)cartKey
{
    return SMUserDefaultGet(OMTempCartKey)?:@"";
}

- (void)setCartKey:(NSString *)cartKey
{
    SMUserDefaultSet(OMTempCartKey, cartKey);
}


- (void)setUserPassword:(NSString *)userPassword
{
    SMUserDefaultSet(kUserPasswordKey, userPassword);
}

- (NSString *)userPassword
{
    return SMUserDefaultGet(kUserPasswordKey);
}

+ (void)saveAuthorizationToken:(NSString *)token{

    if(token == nil||[token isEqualToString:@""]) {
        [SMUserDefault removeObjectForKey:KAuthorizationToken];
        [SMUserDefault synchronize];
        return;

    }
    SMUserDefaultSet(KAuthorizationToken,token);
}

+ (NSString *)authorizationToken
{
    return SMUserDefaultGet(KAuthorizationToken);
}


+ (void)removeImageMemoryCache
{
    [[YYImageCache sharedCache].memoryCache removeAllObjects];
}

+ (void)removeImageDiskCache
{
    [[YYImageCache sharedCache].diskCache removeAllObjects];
}

+ (void)saveCacheGetMethodDataWithUrl:(NSString *)url withData:(id)data
{
    if (![FileManager fileExistsAtPath:KTHttpCacheDirectory isDirectory:nil]) {
        [FileManager createDirectoryAtPath:KTHttpCacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];
    }
    NSString *filePath = [self cachePathWithUrl:url];
    [NSKeyedArchiver archiveRootObject:data toFile:filePath];
}

+ (void)saveCartSectionSelection:(NSDictionary *)sectionSelection
                andCartSelection:(NSDictionary *)selection
{
    SMUserDefaultSet(SM_CART_SECTION_SELECTION_KEY, [sectionSelection mj_JSONString]);
    SMUserDefaultSet(SM_CART_SELECTION_KEY, [selection mj_JSONString]);
}

+ (NSDictionary *)cartSelection
{
    return [SMUserDefaultGet(SM_CART_SELECTION_KEY) mj_JSONObject];
}

+ (NSDictionary *)cartSectionSelection
{
    return [SMUserDefaultGet(SM_CART_SECTION_SELECTION_KEY) mj_JSONObject];
}

+ (id)getCacheByGetMethodWithUrl:(NSString *)url
{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[self cachePathWithUrl:url]];
}

+ (BOOL)removeGetMethodCache
{
    return [FileManager removeItemAtPath:KTHttpCacheDirectory error:nil];
}

+ (NSString *)cachePathWithUrl:(NSString *)url
{
    url = [url stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    url = [url stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    url = [url stringByReplacingOccurrencesOfString:@"?" withString:@"_"];
    url = [url stringByReplacingOccurrencesOfString:@"&" withString:@"_"];
    url = [url stringByReplacingOccurrencesOfString:@"=" withString:@""];
    url = [url stringByReplacingOccurrencesOfString:@"." withString:@"-"];
    return [KTHttpCacheDirectory stringByAppendingPathComponent:url];
}



+ (void)saveImageInCache:(UIImage *)image onCompletion:(void (^)(BOOL isSuccess,NSString *uuid))completion
{

    NSString *uuid = [NSUUID UUID].UUIDString;
    uuid = [uuid stringByAppendingString:@".jpg"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL isSuccess = [FileManager createFileAtPath:[ KTCacheDirectory stringByAppendingPathComponent:uuid]
                                                contents:UIImageJPEGRepresentation(image, .05)
                                              attributes:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            !completion ?: completion(isSuccess,uuid);
        });
    });
}

+ (void)removeImageInCacheWithName:(NSString *)name
{

    [FileManager removeItemAtPath:[ KTCacheDirectory stringByAppendingPathComponent:name] error:nil];
}

+ (id)imageInCacheWithName:(NSString *)name
{
    return [UIImage imageWithContentsOfFile:[ KTCacheDirectory stringByAppendingPathComponent:name]];
}

+ (id)imageURLInCacheWithName:(NSString *)name
{
    return [NSURL fileURLWithPath:[ KTCacheDirectory stringByAppendingPathComponent:name]];
}



@end
